import {Component, ViewChild} from "@angular/core";
import {AlertController, Content, IonicPage, NavController, NavParams, ViewController} from "ionic-angular";
import {Util} from "@providers/util";
import {HttpProvider} from "@providers/http";
import {DialogProvider} from "@providers/dialog";

@IonicPage()
@Component({
    selector: 'page-mquerymaterial',
    templateUrl: 'mquerymaterial.html',
})
export class MqueryMaterialPage {
    @ViewChild(Content) content: Content;
    query_field:any = "";//查询条件
    queryPros: any[] = [];//当前分类的辅材
    choosePros: any[] = this.navParams.get('choosePros');//选中的辅材
    sum: number = 0;//选中辅材的总价
    num: number = 0;//选中辅材的个数
    isClick: boolean = false;//Popover是否显示
    getPros: any[] = this.navParams.get('allPros');//所有的辅材
    categorys: any[] = this.navParams.get('categorys');//所有的辅材类型
    QUANTITY:number;

    constructor(public navCtrl: NavController, public navParams: NavParams,
                private http: HttpProvider, private dialog: DialogProvider,
                private viewCtrl: ViewController,
                private alertCrtl: AlertController,) {
    }

    ionViewDidLoad() {
        this.calculateChoose();
    }

    dismiss(data?: any) {
        if (data) {
            this.viewCtrl.dismiss(data);
            return;
        }
        this.viewCtrl.dismiss();
    }

    updata()
    {
        this.sum=0;
        this.num=0;
        this.choosePros.forEach(value => {
            this.sum =+(this.sum+ +(value.PRICE * value.QUANTITY).toFixed(2)).toFixed(2);
            this.num =+(this.num+ +value.QUANTITY).toFixed(2);
        });
    }
    /**
     * 确定按钮点击事件
     */
    onSubmit() {
        this.dismiss(this.choosePros);
    }

    /**
     * 辅材数量改变点击事件
     * @param pro 选中的商品
     * @param value 为0时表示减小，为1时表示增加
     */
    quantityChange(pro: any, index?: number) {
        switch (index) {
            case 0:
                if (pro.QUANTITY == 0) return;
                pro.QUANTITY = +(pro.QUANTITY-1).toFixed(2);
                if  (pro.QUANTITY < 0){
                    pro.QUANTITY = 0;
                }
                this.queryPros.forEach(value => {
                        if (pro.ZJ == value.ZJ) {
                            value.QUANTITY = +(value.QUANTITY-1).toFixed(2);
                            if  (value.QUANTITY < 0){
                                value.QUANTITY = 0;
                            }
                        }

                });
                break;
            case 1:
                pro.QUANTITY = +(+pro.QUANTITY+1).toFixed(2);
                this.queryPros.forEach(value => {
                    if (pro.ZJ == value.ZJ) {
                        value.QUANTITY = +(+value.QUANTITY+1).toFixed(2);
                    }

                });
                break;
        }
        this.calculateChoose();
    }
    currentQuantityChange(pro: any, index?: number){
        switch (index) {
            case 0:
                if (pro.QUANTITY == 0) return;
                pro.QUANTITY = +(pro.QUANTITY-1).toFixed(2);
                if  (pro.QUANTITY < 0){
                    pro.QUANTITY = 0;
                }
                this.getPros.forEach(value => {
                    value.forEach(val => {
                        if (pro.ZJ == val.ZJ) {
                            val.QUANTITY = +(val.QUANTITY-1).toFixed(2);
                            if  (val.QUANTITY < 0){
                                val.QUANTITY = 0;
                            }
                        }
                    });
                });
                break;
            case 1:
                pro.QUANTITY = +(+pro.QUANTITY+1).toFixed(2);
                this.getPros.forEach(value => {
                    value.forEach(val => {
                        if (pro.ZJ == val.ZJ) {
                            val.QUANTITY = +(+val.QUANTITY+1).toFixed(2);
                        }
                    });
                });
                break;

        }

        this.calculateChoose();

    }

    //失去焦点改变辅材数量
    eqc(pro: any) {
        this.editChange(pro);
    }

    //点击enter改变辅材数量
    kdqc(event,pro:any) {
        if (event.keyCode == 13) {
            this.editChange(pro);
        }
    }

    editChange(pro:any){
        this.getPros.forEach(val => {
            val.forEach(value => {
                if (value.ZJ == pro.ZJ) {
                    if (pro.QUANTITY == null) {
                        value.QUANTITY = 0
                        pro.QUANTITY =0
                    } else {
                        pro.QUANTITY = +pro.QUANTITY.toFixed(2);
                        if(pro.QUANTITY<0){
                            pro.QUANTITY=0;
                        }
                        value.QUANTITY = pro.QUANTITY
                    }
                }
            })
        });
        this.queryPros.forEach(value => {
                if (value.ZJ == pro.ZJ) {
                    if (pro.QUANTITY == null) {
                        value.QUANTITY = 0
                        pro.QUANTITY =0
                    } else {
                        pro.QUANTITY = +pro.QUANTITY.toFixed(2);
                        if(pro.QUANTITY<0){
                            pro.QUANTITY=0;
                        }
                        value.QUANTITY = +pro.QUANTITY;
                    }
                }
        })
        this.calculateChoose();
    }

    /**
     * 格式化选中的辅材，并计算个数和总费用
     */
    calculateChoose() {
        //获取所有的数量不为0的辅材
        let temp = [];
        this.getPros.forEach(value => {
            value.forEach(val => {
                temp.push(val);
            })
        });
        this.choosePros = temp.filter(value => {
            return value.QUANTITY > 0;

        });
        //计算数量不为0的辅材的个数和总价
        this.sum = 0;
        this.num = 0;
        this.choosePros.forEach(value => {
            this.sum = +(this.sum+ +(value.PRICE * value.QUANTITY).toFixed(2)).toFixed(2);
            this.num = +(this.num+ +value.QUANTITY).toFixed(2);
        });
        if (this.num == 0) {
            this.isClick = false;
        }

    }


    /**
     * 清空选中的辅材
     */
    clearAll() {
        this.dialog.showConfirm(() => {
            this.choosePros.forEach(value => {
                value.QUANTITY = 0;
            });
            this.queryPros.forEach(value => {
                value.QUANTITY = 0;
            });
            this.calculateChoose();
        }, "是否清空所有已选中的辅材！");
    }

    //失去焦点查询
    sJq() {
        if (!Util.isNull(this.query_field)) {
            this.query();
        }
    }

    //点击enter查询
    shuRus(event) {
        if (event.keyCode == 13) {
            this.query();
        }
    }

    query() {
        console.log(this.query_field);
        this.http.post("/Inbound/invoke.do", {
            interfaceId: "csm.css.getFCFLSPFC",
            data: JSON.stringify({
                'SPMC': this.query_field,
            })
        }).subscribe(
            message => {
                this.queryPros = message.data;
                this.queryPros.forEach(value => {
                  console.log("value:" + value);
                    value.QUANTITY = 0;
                    this.getPros.forEach(val => {
                      console.log("va:" + val);
                        val.forEach(val2 => {
                          console.log("val2:" + val2);
                            if (value.ZJ == val2.ZJ) {
                                value.QUANTITY = val2.QUANTITY;
                            }
                        });
                    });
                });
                this.calculateChoose();
            },
            error => {
                this.dialog.showAlert("请检查网络");
            });
    }
  setPrice(item) {
    let alert = this.alertCrtl.create({
      message: "输入价格",
      inputs: [{type: 'number', name: 'price'}],
      buttons: [{
        text: "取消", handler: () => {
        }
      }, {
        text: "确定", handler: (res) => {
          if (item.oldPic>res.price){
            return this.dialog.showAlert("收费价格低于限价， 请调整价格。")
          }
          item.PRICE = res.price;
          this.updata();
        }
      }]
    });
    alert.present();
  }
}
